package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.etoak.common.core.enums.OrderStateEnum;
import com.etoak.common.web.context.LoginContext;
import com.etoak.config.OrderQueueConfig;
import com.etoak.dto.OrderDTO;
import com.etoak.entity.Order;
import com.etoak.mapper.OrderMapper;
import com.etoak.service.OrderItemService;
import com.etoak.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author etoak
 * @since 2024-12-24
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void create(OrderDTO orderDTO) {
        // 订单编号 Twitter 分布式 id 雪花算法
        String orderNo = IdUtil.getSnowflakeNextIdStr();

        // 订单
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setUserId(Integer.parseInt(LoginContext.getUserId()));
        order.setOrderState(OrderStateEnum.CREATE.getState());
        order.setCreateTime(DateUtil.now());
        order.setPrepareTime(orderDTO.getPrepareTime());

        // 保存订单
        this.save(order);

        orderDTO.getItemList().forEach(item -> item
                .setOrderNo(orderNo));

        orderItemService.saveBatch(orderDTO.getItemList());

        // 发送消息
        rabbitTemplate.convertAndSend(OrderQueueConfig.EXCHANGE,
                OrderQueueConfig.KEY,
                orderNo,
                message -> {
                    message.getMessageProperties().setDelayLong(1000L *10);
                    return message;
                });
    }
}
